# -*- coding: utf-8 -*-
from crypt import methods
from flask import jsonify, request
from framework.model import Pusher as PusherModel, PusherWebhook as PusherWebhookModel
from framework.logic.common import DingTalkLogic, CommonLogic
from . import api_blue

# 发送消息
@api_blue.route("/pusher/send-msg/<secret>", methods=["POST"])
def senMsg(secret):
    try:
        if not request.is_json:
            raise ValueError("request请求必须是json请求")
        params = request.json
        pusher = PusherModel.query.filter(PusherModel.pusher_secret == secret).first()
        if not pusher:
            raise ValueError("Puser不存在")
        product_type = params['product_type'] if 'product_type' in params else 'DingTalk'
        pusher_webhook = PusherWebhookModel.query.filter(PusherWebhookModel.pusher_id==pusher.id, PusherWebhookModel.pusher_type==product_type).first()
        webhook = pusher_webhook.webhook
        secret = pusher_webhook.secret
        msg_handle = DingTalkLogic(webhook, secret)
        res = msg_handle.sendMsg(params)
        if res['errcode'] == 0:
            code = 200
            err_msg = "success"
            return jsonify({"code":200, "msg":"success"})
        else:
            raise ValueError("请求失败，失败愿意：{}" . format(res['errmsg']))
    except Exception as e:
        code = 400
        err_msg = repr(e)
        return jsonify({"code":400, "msg":repr(e)})
    finally:
        CommonLogic.writeLog(pusher_webhook, params, code, err_msg)